<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" th:replace="layout :: layout">
<head>
    <th:block th:fragment="page-styles">
        <style>
            .config-card {
                transition: all 0.3s ease;
                border: 1px solid #e0e0e0;
            }
            
            .config-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                border-color: #667eea;
            }
            
            .config-header {
                background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
                border-bottom: 1px solid #e0e0e0;
                padding: 15px 20px;
            }
            
            .config-actions {
                display: flex;
                gap: 8px;
                flex-wrap: wrap;
            }
            
            .config-meta {
                font-size: 0.85rem;
                color: #6c757d;
            }
            
            .scenario-badge {
                background-color: #e3f2fd;
                color: #1976d2;
                border: 1px solid #bbdefb;
                padding: 2px 8px;
                border-radius: 12px;
                font-size: 0.75rem;
                font-weight: 500;
            }
            
            .empty-state {
                text-align: center;
                padding: 60px 20px;
                color: #6c757d;
            }
            
            .empty-state .empty-icon {
                font-size: 4rem;
                margin-bottom: 20px;
                opacity: 0.5;
            }
        </style>
    </th:block>
</head>

<main th:fragment="content">
    <!-- 页面头部 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2>
                <i class="fas fa-cogs me-2"></i>
                场景配置管理
            </h2>
            <p class="text-muted mb-0">创建和管理HTTP性能测试场景配置</p>
        </div>
        <div>
            <a href="/configs/new" class="btn btn-primary btn-lg">
                <i class="fas fa-plus me-2"></i>
                创建新场景
            </a>
        </div>
    </div>

    <!-- 工具栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="fas fa-search"></i>
                        </span>
                        <input type="text" class="form-control" id="search-input" placeholder="搜索配置名称或描述...">
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <button class="btn btn-outline-secondary" onclick="refreshConfigs()">
                        <i class="fas fa-sync-alt me-1"></i>
                        刷新
                    </button>
                    <button class="btn btn-outline-secondary" onclick="exportConfigs()">
                        <i class="fas fa-download me-1"></i>
                        导出
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-spinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在加载配置列表...</p>
    </div>

    <!-- 配置列表 -->
    <div id="configs-container">
        <!-- 配置卡片将通过JavaScript动态加载 -->
    </div>

    <!-- 空状态 -->
    <div id="empty-state" class="empty-state" style="display: none;">
        <div class="empty-icon">
            <i class="fas fa-folder-open"></i>
        </div>
        <h4>暂无配置</h4>
        <p class="mb-4">还没有创建任何测试场景配置，点击下面的按钮开始创建第一个配置。</p>
        <a href="/configs/new" class="btn btn-primary btn-lg">
            <i class="fas fa-plus me-2"></i>
            创建第一个场景
        </a>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle text-warning me-2"></i>
                        确认删除
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除配置 "<span id="delete-config-name"></span>" 吗？</p>
                    <p class="text-danger small mb-0">
                        <i class="fas fa-info-circle me-1"></i>
                        此操作不可撤销，配置文件将被永久删除。
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirm-delete-btn">
                        <i class="fas fa-trash me-1"></i>
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>
</main>

<th:block th:fragment="page-scripts">
    <script>
        let allConfigs = [];
        let deleteConfigId = null;
        
        $(document).ready(function() {
            loadConfigs();
            
            // 搜索功能
            $('#search-input').on('input', function() {
                filterConfigs();
            });
            
            // 删除确认
            $('#confirm-delete-btn').click(function() {
                if (deleteConfigId) {
                    deleteConfig(deleteConfigId);
                }
            });
        });
        
        function loadConfigs() {
            AppUtils.showLoading();
            $('#empty-state').hide();
            
            $.get('/api/configs')
                .done(function(configs) {
                    allConfigs = configs;
                    renderConfigs(configs);
                })
                .fail(function() {
                    AppUtils.showError('加载配置列表失败');
                })
                .always(function() {
                    AppUtils.hideLoading();
                });
        }
        
        function renderConfigs(configs) {
            const container = $('#configs-container');
            container.empty();
            
            if (configs.length === 0) {
                $('#empty-state').show();
                return;
            }
            
            $('#empty-state').hide();
            
            const html = configs.map(config => `
                <div class="col-md-6 col-lg-4 mb-4 config-item" data-config-id="${config.id}">
                    <div class="card config-card h-100">
                        <div class="config-header">
                            <h5 class="mb-1">${escapeHtml(config.testName)}</h5>
                            <div class="config-meta">
                                <i class="far fa-clock me-1"></i>
                                ${AppUtils.formatTime(config.lastModified)}
                            </div>
                        </div>
                        <div class="card-body">
                            <p class="card-text text-muted small mb-3">
                                ${escapeHtml(config.description || '无描述')}
                            </p>
                            
                            <div class="row text-center mb-3">
                                <div class="col-4">
                                    <div class="small text-muted">并发用户</div>
                                    <strong>${config.concurrentUsers}</strong>
                                </div>
                                <div class="col-4">
                                    <div class="small text-muted">持续时间</div>
                                    <strong>${config.testDurationSeconds}s</strong>
                                </div>
                                <div class="col-4">
                                    <div class="small text-muted">场景数</div>
                                    <strong>${config.scenarioCount}</strong>
                                </div>
                            </div>
                            
                            <div class="config-actions">
                                <button class="btn btn-primary btn-sm" onclick="startTest('${config.id}')">
                                    <i class="fas fa-play me-1"></i>
                                    执行测试
                                </button>
                                <a href="/configs/${config.id}/edit" class="btn btn-outline-secondary btn-sm">
                                    <i class="fas fa-edit me-1"></i>
                                    编辑
                                </a>
                                <button class="btn btn-outline-info btn-sm" onclick="duplicateConfig('${config.id}')">
                                    <i class="fas fa-copy me-1"></i>
                                    复制
                                </button>
                                <button class="btn btn-outline-danger btn-sm" onclick="confirmDelete('${config.id}', '${escapeHtml(config.testName)}')">
                                    <i class="fas fa-trash me-1"></i>
                                    删除
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
            
            container.html('<div class="row">' + html + '</div>');
        }
        
        function filterConfigs() {
            const query = $('#search-input').val().toLowerCase();
            
            if (!query) {
                renderConfigs(allConfigs);
                return;
            }
            
            const filtered = allConfigs.filter(config => 
                config.testName.toLowerCase().includes(query) ||
                (config.description && config.description.toLowerCase().includes(query))
            );
            
            renderConfigs(filtered);
        }
        
        function refreshConfigs() {
            loadConfigs();
        }
        
        function startTest(configId) {
            const startButton = event.target.closest('button');
            const originalContent = startButton.innerHTML;
            
            startButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>启动中...';
            startButton.disabled = true;
            
            $.ajax({
                url: '/api/tests/start',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ configId: configId })
            })
            .done(function(response) {
                if (response.success) {
                    AppUtils.showSuccess('测试启动成功');
                    // 跳转到测试监控页面
                    setTimeout(() => {
                        window.location.href = '/tests/' + response.sessionId + '/monitor';
                    }, 1000);
                } else {
                    AppUtils.showError(response.message || '测试启动失败');
                }
            })
            .fail(function() {
                AppUtils.showError('测试启动失败');
            })
            .always(function() {
                startButton.innerHTML = originalContent;
                startButton.disabled = false;
            });
        }
        
        function duplicateConfig(configId) {
            AppUtils.showInfo('功能开发中...');
        }
        
        function confirmDelete(configId, configName) {
            deleteConfigId = configId;
            $('#delete-config-name').text(configName);
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }
        
        function deleteConfig(configId) {
            $.ajax({
                url: '/api/configs/' + configId,
                method: 'DELETE'
            })
            .done(function(response) {
                if (response.success) {
                    AppUtils.showSuccess('配置删除成功');
                    bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                    loadConfigs(); // 重新加载列表
                } else {
                    AppUtils.showError(response.message || '配置删除失败');
                }
            })
            .fail(function() {
                AppUtils.showError('配置删除失败');
            });
        }
        
        function exportConfigs() {
            AppUtils.showInfo('导出功能开发中...');
        }
        
        function escapeHtml(text) {
            if (!text) return '';
            return text.replace(/[&<>"']/g, function(match) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#39;'
                }[match];
            });
        }
    </script>
</th:block>
</html>